package org.charry.lib.database_utility;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * A class to load configuration for this factory.
 * 
 * The configuration is located at config/config_database.xml
 * 
 * @author wcharry
 * 
 */
public class DatabaseConfig {
	private static Log log = LogFactory.getLog(DatabaseConfig.class);

	private String strDbUser;
	private String strDbPassword;
	private String strDbUrl;
	private String strDbDriver;
	private String strDbAlias;

	/**
	 * Init the database factory.
	 * 
	 * @param alias
	 *            database alias
	 */
	public DatabaseConfig(final String alias) {
		strDbAlias = alias;

		init();
	}

	/**
	 * Configuration file sample:
	 * 
	 * <pre>
	 * &lt;config&gt;
	 *         &lt;database&gt;
	 *                 &lt;apple&gt;
	 *                         &lt;username&gt;username&lt;/username&gt;
	 *                         &lt;password&gt;passwd&lt;/password&gt;
	 *                         &lt;url&gt;jdbc:mysql://hostname/dbname?autoReconnect=true&lt;/url&gt;
	 *                         &lt;driver&gt;com.mysql.jdbc.Driver&lt;/driver&gt;
	 *                 &lt;/apple&gt;
	 *         &lt;/database&gt;
	 * &lt;/config&gt;
	 * </pre>
	 */
	public void init() {
		try {
			Configuration config = new XMLConfiguration(
					"config/config_database.xml");

			this.strDbUser = config.getString("database." + strDbAlias
					+ ".username");
			log.info("username:" + strDbUser);
			this.strDbPassword = config.getString("database." + strDbAlias
					+ ".password");
			this.strDbUrl = config.getString("database." + strDbAlias + ".url");
			log.info("conn string:" + strDbUrl);
			this.strDbDriver = config.getString("database." + strDbAlias
					+ ".driver");
		} catch (Exception e) {
			log.error(e);
		}
	}

	public String getStrDbUser() {
		return strDbUser;
	}

	public String getStrDbPassword() {
		return strDbPassword;
	}

	public String getStrDbUrl() {
		return strDbUrl;
	}

	public String getStrDbDriver() {
		return strDbDriver;
	}
}
